qui(
    function(require, exports, module) {

        News.Grid = function(options) {
            this.dao = News.Dao;
            this.config = News.Config;
            this.util = News.Util;
            this.options = options || {};
			//this.channel_id = Com.url.getQueryValue("channel_id",location.href);
			//this.channel_name = Com.url.getQueryValue("channel_name",location.href);
            this.construct = options.construct || function() {
                this.init();
            };
            this.construct.call(this);
        };

        Com.inherits(News.Grid, Ancestor.Grid).extend({
            init: function() {
                var self = this;
                var $container = self.options.$container;
                self.$grid = $container.find('table.grid');
                self.perpareData();
                self.bindBasicEvent();
                //self.initSuggest();
            },

            perpareData: function() {
                var self = this;
                var username = $("div.user a.name").html();
                var requestData = {url: News.urlConfig.machinelistUrl, type: "get",
                                                    params: {type: 0, area: 0, username: username, _: new Date().getTime(), from_client: true }
                                                  };
                self.dao.redirect({"request": JSON.stringify(requestData), "timeSign": new Date().getTime()}, function (data) {
                    var parentJDom = $("select[name=channel_area]");
                    var hasDataRegion = [];

                    $("<option>", {value: "all", html: "全部"}).appendTo(parentJDom);

                    if (data != null && data.response != null && data.response.list) {
                        $.each(data.response.list, function (index, obj) {
                            if (obj[1] >= 0 && obj[1] <= 2) {
                                if (hasDataRegion.indexOf(obj[1]) == -1) {
                                    hasDataRegion.push(obj[1]);
                                }

                                News.Config.IP_LINK_AREA[obj[0]] = obj[0] + "[" + News.Config.REGION_LIST[obj[1]] + "]";
                            }
                        });
                        $.each(hasDataRegion, function (i, element) {
                            $("<option>", {
                                value: element,
                                html: News.Config.REGION_CH_LIST[element]
                            }).appendTo(parentJDom);
                        })
                    } else {
                        console.log("wait to do");
                    }
                });
            },

            bindBasicEvent: function() {
                var self = this;
                jQuery.validator.addMethod("isValidTime", function(value, element, param) {
                    var isValidTime = function(timeStr) {
                        var date = '00:00';
                        var formatTime = /^(\d{2}):(\d{2})$/
                        if (!timeStr || timeStr == "") {
                            return true;
                        }
                        if ((timeStr.length < date.length) || ('string' !== typeof timeStr) || !formatTime.test(timeStr)) {
                            return false;
                        }
                        try {
                            var parts = (timeStr || '').split(':');
                            if (parts.length > 2) {
                                return false;
                            }

                            var hour   = Number(parts[0]).toFixed(0);
                            var minute = Number(parts[1]).toFixed(0);

                            if ((parts[0].indexOf('.') != -1) || (parts[1].indexOf('.') != -1)) {
                                return false;
                            }
                            if (isNaN(hour) || isNaN(minute)) {
                                return false;
                            }
                            if ((hour>=0 && hour<24) && (minute >= 0 && minute<60)) {
                                return true;
                            }
                        } catch (e) {
                            console.log(e.message);
                        }
                        return false;
                    };

                    return isValidTime(value);
                });

                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                self.bindFormEvent($form);
                $container.find('.query-btn').on('click.query', function() {
                    self.query();
                    return false;
                });

                $form.find('.query-add').click(function() {
					window.open("/epg/news_edit.html");
                });

                $form.find('#news-details').click(function() {
                    window.open("/epg/news_details.html");
                });

                $form.find('#news-statistic').click(function() {
                    window.open("/epg/news_statistic.html");
                });

				$("[type=reset]").click(function(){
                    $("form[name=basicFrm]")[0].reset();
                    $("select[name=channel_area]").change();
				});

                $("select[name=channel_area]").bind("change", function (event) {
                    var selectJDom = $("#filter_source_ip");
                    selectJDom.html("");
                    var username = $("div.user a.name").html();
                    var requestData = {url: News.urlConfig.machinelistUrl, type: "get",
                                                        params: {type: 0, area: 0, username: username, _: new Date().getTime(), from_client: true }
                                                      };

                    self.dao.redirect({"request": JSON.stringify(requestData), "timeSign": new Date().getTime()}, function(data) {
                        var responseData = data;
                        var eqVal = event.currentTarget.value == "all" ? null : parseInt(event.currentTarget.value);
                        $("<option value='all'>全部</option>").appendTo(selectJDom);
                        if (responseData != null && responseData.response != null && responseData.response.list != null) {
                            $.each(responseData.response.list, function (i, obj) {
                                if ((eqVal == null && obj[1] >= 0 && obj[1] <= 2) || eqVal == obj[1]) {
                                    $("<option>", {
                                        value: obj[0],
                                        html: News.Config.IP_LINK_AREA[obj[0]]
                                    }).appendTo(selectJDom);
                                }
                            })
                        }
                    });

                });
                $("select[name=channel_area]").change();
			},

			bindFormEvent: function($form) {
                var self = this;
                $form.find('input[name="start_time"]').timepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="start_time"]').timepicker("option", selectedDate);
                    },
                    timeFormat: 'HH:mm'
                });
                $form.find('input[name="stop_time"]').timepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="stop_time"]').timepicker("option", selectedDate);
                    },
                    timeFormat: 'HH:mm'
                });

			},

            run: function(options, callback) {
                var self = this;
                var gridConfig = self.getGridConfig();
                options = $.extend(true, {
                    width: 1700,
                   // multiselect: true,
                    //multiselectWidth: 30,
                    shrinkToFit: false,
                    // idPrefix: 'Video-',
                    autowidth: false
                }, gridConfig, options);
                self.$grid.jqGrid(options);

              //  self.initGrid.call(this, options, callback);
                //TODO self.loadTableByDate();
                 self.echoQuery();
            },

            getParam: function() {
                var self = this;
                var $container = self.options.$container;

                var $grid = self.$grid;
                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function(item) {
					return true;
                });

				var checkboxVal = [];
                var name;
                var key;
                $.each($elements, function() {
                    name = this.name;
                    if (name) {
						if(name=='repeat_info')	{
							if(this.checked){
								checkboxVal.push($(this).val());
							}
						} else if ((name=='channel_area' && $(this).val()=='all') || (name=='channel_ip' && $(this).val()=='all')){
						} else {
							if($(this).val()){
								params[name] = $(this).val();
							}
						}
                    }

                });
				if(checkboxVal.length!==0){
					params['repeat_info']=JSON.stringify(checkboxVal);//params['repeat_info'].join(',');
				}
                return params;
            },
            loadTableByDate:function(){
                var self = this;
                self.$grid.setGridParam({page: 1, url:'/api/redirect' , loadtext: '加载中...',
                    datatype:"json",
                    loadui: "block",
                    postData:{"request": JSON.stringify({url: "http://lego.iqiyi.com/live2VOD/preSet/get", type: "get", params:{channel_id: self.channel_id} , needCookie: false})}
                    }).trigger("reloadGrid");
            },

            query: function() {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var params = self.getParam();
                var validator = self.getValidator();
                var success = validator.form();
                if (success) {
                    self.config.PageBean = EpgWeb.Util.createPageBean();
                    self.dao.getList(params, function (data) {
                         var retValue = null;
                         if (data.code === 200 && data.response != null && data.response.list != null) {
                             self.config.PageBean.setNewData(data.response.list);
                         } else {
                             self.config.PageBean.setNewData([]);
                         }
                         retValue = self.config.PageBean.getCur();
                         self.$grid[0].addJSONData(retValue);
                         self.showNoData(self.$grid);
                     });
                 }
            },
            getValidator: function() {
                var $form = $("form[name='basicFrm']");
                var validator = Validator.getValidator($form, News.Config.queryValidator);

                return validator;
            },
            showNoData: function (jqGridTarget) {
                var re_records = jqGridTarget.getGridParam('records');
                var parentElement = jqGridTarget.parent();
                var norecordElement = parentElement.find(".norecords")
                if (re_records == 0 || re_records == null) {
                    if (norecordElement.html() == null) {
                        parentElement.append('<div class="norecords">没有符合数据</div>');
                        norecordElement.hide();
                    }
                    norecordElement.show();
                } else {
                    norecordElement.hide();
                }
            }

        });

    }
);